<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-popconfirm
            v-if="item.btnKey === 'btnQx'"
            title="是否确认取消发布？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleQxFb(0)"
          >
            <a-button :key="index" :type="item.color" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            v-else-if="item.btnKey === 'btnFb'"
            title="是否确认发布？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleQxFb(1)"
          >
            <a-button :key="index" :type="item.color" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            v-else-if="item.btnKey === 'btnUnenable'"
            title="是否确认停用存货？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleUnEnableInv()"
          >
            <a-button :key="index" :type="item.color" v-auth="item.auth">
              <Icon :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-button v-else :key="index" :type="item.color" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ cinvcode: record.cinvcode })">
          {{ record.cinvname }}
        </a>
      </template>
      <template #picUrl="{ record }">
        <a-image
          :width="50"
          :src="record.picUrl ? ctxPath + record.picUrl : '/resource/img/noSet.png'"
        />
      </template>
      <template v-if="hasPermission(['shop:shopInv:edit'])" #uploadFile="{ record }">
        <BasicUpload
          v-model:value="record.dataMap"
          :bizKey="record.id"
          :bizType="'shopInv_image'"
          :uploadType="'image'"
          :maxNumber="2"
          :maxSize="1"
          :loadTime="record.__t"
          :showPreview="true"
          :emptyHidePreview="true"
          @change="selPicChange($event, record.id)"
        />
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <BasicDrawer
      v-bind="$attrs"
      @register="registerAppsetDetailsDrawer"
      :showFooter="false"
      width="90%"
      :maskClosable="true"
      :title="'商品详情'"
    >
      <AppsetDetails :cinvcode="cinvcode" />
    </BasicDrawer>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasInvBasInvList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, ref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable } from '/@/components/Table';
  import {
    basInvDelete,
    updateFbStatus,
    savePic,
    disableInv,
    enableInv,
  } from '/@/api/bas/inv/basInv';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import { BasicUpload } from '/@/components/Upload';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicDrawer } from '/@/components/Drawer';
  import AppsetDetails from '../../../shop/appsetDetails/list.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  const { ctxPath } = useGlobSetting();

  const { hasPermission } = usePermission();
  const [registerAppsetDetailsDrawer, { openDrawer: openAppsetDetailsDrawer }] = useDrawer();

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  const { t } = useI18n('bas.inv.basInv');
  const { showMessage } = useMessage();

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  let cinvcode = ref('');

  const actionColumn: BasicColumn = {
    width: 120, //操作按钮宽度
    // actions: (record: Recordable) => {
    //   actionColumnData.value.forEach((item) => {
    //     if (item.title == '编辑') {
    //       item.onClick = () => handleForm({ cinvcode: record.cinvcode });
    //     }
    //     if (item.title == '删除') {
    //       item.popConfirm = {
    //         title: '是否确认删除数据',
    //         confirm: handleDelete.bind(this, { cinvcode: record.cinvcode }),
    //       };
    //     }
    //   });
    //   return actionColumnData.value;
    // },
    actions: (record: Recordable) => [
      {
        icon: 'clarity:timeline-line',
        title: t('详情配置'),
        onClick: handleDetails.bind(this, { cinvcode: record.cinvcode }),
        // auth: 'test:testData:edit',
      },
    ],
  };

  const [registerTable, { reload, setProps, getForm, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  onMounted(async () => {
    const res = await listSet({ viewCode: 'bas_inv_list001' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey == 'btnAdd') {
        item.do = () => handleForm({});
      }
      if (item.btnKey == 'btnQx') {
        item.color = 'error';
        item.do = () => handleQxFb(0);
      }
      if (item.btnKey == 'btnFb') {
        item.color = 'success';
        item.do = () => handleQxFb(1);
      }
      if (item.btnKey == 'btnEnvaleInv') {
        // 启用存货
        item.color = 'success';
        item.do = () => handleEnableInv();
      }
      if (item.btnKey == 'btnUnenable') {
        // 停用存货
        item.color = 'warning';
        item.do = () => handleUnEnableInv();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [registerDrawer, { openDrawer }] = useDrawer();

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        clsCode: props.treeCode,
        'basInv.invCls.treeName': props.treeName,
      });
      reload();
    },
  );
  function handleDetails(record: Recordable) {
    cinvcode.value = record.cinvcode;
    // cversion.value = record.cversion;
    // title.value = `首页配置 （版本号：${record.cversion}）`;
    openAppsetDetailsDrawer(true);
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }
  async function selPicChange(fileList, id) {
    console.log(id);
    console.log(fileList);
    await savePic({ id, dataMap: fileList });
    reload();
  }

  async function handleDelete(record: Recordable) {
    const res = await basInvDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleQxFb(ope) {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      const res = await updateFbStatus({ selIds: selIds.value, ope: ope });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  // 启用存货
  async function handleEnableInv() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      console.log(selIds);
      const res = await enableInv({ selIds: selIds.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  // 停用存货
  async function handleUnEnableInv() {
    if (getSelectRows().length) {
      var selIds = ref('');
      getSelectRows().forEach((item) => {
        selIds.value += item.id + ',';
      });
      console.log(selIds);
      const res = await disableInv({ selIds: selIds.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage('请选择一行数据！！');
    }
  }

  function handleSuccess() {
    reload();
  }
</script>
